<?php

namespace app\common\services;

use app\common\exceptions\ErrException;
use app\common\Facade\Log;
use think\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UploadService
{
    /**
     * @var Auth
     */
    protected $auth;

    /**
     * @var mixed
     */
    private $ak;

    /**
     * @var mixed
     */
    private $sk;

    /**
     * @var mixed
     */
    private $bucket;

    /**
     * @var mixed
     */
    private $domain;

    /**
     * @var
     */
    private $upManager;

    /**
     * Upload constructor.
     * @param Request $request
     */
    public function __construct()
    {
		$this->ak        = env('QINIU.AK');
		$this->sk        = env('QINIU.SK');
		$this->bucket    = env('QINIU.BUCKET');
		$this->domain    = env('QINIU.DOMAIN');
        $this->auth      = new Auth($this->ak, $this->sk);
        $this->upManager = new UploadManager();
    }
    
    public function uploadStream($stream,$prefix,$ext){
		// 生成上传的token
		$token    = $this->auth->uploadToken($this->bucket);
		$fileName = $prefix . '/' . md5(uniqid(rand(1, 100000))) . ".{$ext}";
		// 文件上传
		list($ret, $error) = $this->upManager->put($token, $fileName, $stream);
		if ($error !== null) {
			ErrException::throwExcep(-1, '上传失败:'.json_encode($error));
		}
		return $this->domain . $ret['key'];
	}
}
